package cn.regexp.business.web.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.regexp.business.web.model.OrderModel;
import cn.regexp.common.base.page.TablePageInfo;
import cn.regexp.common.web.AjaxResult;
import cn.regexp.domain.ShopConsignee;
import cn.regexp.domain.ShopOrder;
import cn.regexp.domain.ShopUser;
import cn.regexp.query.OrderQuery;
import cn.regexp.service.IConsigneeService;
import cn.regexp.service.IOrderService;
import cn.regexp.service.IShopUserService;
import cn.regexp.utils.CommonUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 订单控制器
 */
@Controller
@RequestMapping("business/orders")
public class OrderController {
    //模板前缀
    private static final String prefix = "business/orders/";

    @Autowired
    private IOrderService ordersService;
    @Autowired
    private IShopUserService userService;
    @Autowired
    private IConsigneeService consigneeService;

    //页面------------------------------------------------------------
    //列表
    @RequiresPermissions("business:orders:view")
    @RequestMapping("/listPage")
    public String listPage() {
        return prefix + "list";
    }

    @RequiresPermissions("business:orders:edit")
    @RequestMapping("/editPage")
    public String editPage(Long id, Model model) {
        model.addAttribute("orders", ordersService.getById(id));
        return prefix + "edit";
    }

    //明细
    @RequiresPermissions("business:orders:detail")
    @RequestMapping("/detail")
    public String detail(Long orderId, Model model) {
        ShopOrder shopOrder = ordersService.getById(orderId);
        OrderModel orderModel = new OrderModel();
        BeanUtils.copyProperties(shopOrder, orderModel);
        ShopUser user = userService.getById(shopOrder.getUserId());
        ShopConsignee consignee = consigneeService.getById(shopOrder.getConsigneeId());
        orderModel.setUsername(Objects.requireNonNull(user).getUsername());
        orderModel.setConsigneeName(Objects.requireNonNull(consignee).getConsigneeName());
        orderModel.setFullAddress(CommonUtil.getFullAddress(consignee));
        model.addAttribute("order", orderModel);
        return prefix + "detail";
    }

    //数据-----------------------------------------------------------
    //列表
    @RequiresPermissions("business:orders:list")
    @RequestMapping("/query")
    @ResponseBody
    public TablePageInfo<OrderModel> query(OrderQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        QueryWrapper<ShopOrder> wrapper = new QueryWrapper<>();
        wrapper.like(ObjectUtil.isNotEmpty(qo.getOrderSn()), "order_sn", qo.getOrderSn())
                .like(ObjectUtil.isNotEmpty(qo.getMobile()), "mobile", qo.getMobile())
                .eq(ObjectUtil.isNotEmpty(qo.getType()), "type", qo.getType())
                .eq(ObjectUtil.isNotEmpty(qo.getOrderState()), "order_state", qo.getOrderState())
                .eq(ObjectUtil.isNotEmpty(qo.getPayState()), "pay_state", qo.getPayState())
                .orderByDesc("order_time");
        List<ShopOrder> shopOrderList = ordersService.list(wrapper);
        List<OrderModel> list = new ArrayList<>(shopOrderList.size());
        if (ObjectUtil.isNotEmpty(shopOrderList)) {
            shopOrderList.forEach(item -> {
                OrderModel model = new OrderModel();
                BeanUtils.copyProperties(item, model);
                ShopUser user = userService.getById(item.getUserId());
                ShopConsignee consignee = consigneeService.getById(item.getConsigneeId());
                model.setUsername(Objects.requireNonNull(user).getUsername());
                model.setConsigneeName(Objects.requireNonNull(consignee).getConsigneeName());
                model.setFullAddress(CommonUtil.getFullAddress(consignee));
                list.add(model);
            });
        }
        return new TablePageInfo<>(list, ordersService.count(wrapper));
    }



    //编辑
    @RequiresPermissions("business:orders:edit")
    @RequestMapping("/edit")
    @ResponseBody
    public AjaxResult edit(ShopOrder order) {
        ordersService.updateById(order);
        return AjaxResult.success();
    }

    //删除
    @RequiresPermissions("business:orders:remove")
    @RequestMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        ordersService.removeByIds(Collections.singletonList(ids));
        return AjaxResult.success();
    }

    // 确认
    @RequiresPermissions("business:orders:confirm")
    @RequestMapping("/confirm")
    @ResponseBody
    public AjaxResult confirm(String orderId) {
        UpdateWrapper<ShopOrder> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", orderId)
                .set("order_state", ShopOrder.ORDER_NOT_DELIVERY);
        ordersService.update(wrapper);
        return AjaxResult.success();
    }

    // 退款
    @RequiresPermissions("business:orders:refund")
    @RequestMapping("/refund")
    @ResponseBody
    public AjaxResult refund(String orderId) {
        UpdateWrapper<ShopOrder> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", orderId)
                .set("order_state", ShopOrder.ORDER_REFUND)
                .set("pay_state", ShopOrder.PAY_REFUND)
                .set("refund_time", DateUtil.date());
        ordersService.update(wrapper);
        return AjaxResult.success();
    }
}
